<template>
  <section class="wrap">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="ruleForm.nickName" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="ruleForm.phone" />
      </el-form-item>
      <el-form-item label="用户密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" />
      </el-form-item>
      <el-form-item label="押金" prop="yajin">
        <el-input v-model.number="ruleForm.yajin" disabled type="number" />
      </el-form-item>

      <el-form-item label="邀请人" prop="parent">
        <el-select style="width: 100%;" v-model="ruleForm.parent" placeholder="请选择邀请人">
          <el-option v-for="item in getUser(null)" :key="'user' + item.id" :label="item.nickName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="收款二维码" prop="img">
        <el-upload class="avatar-uploader" :limit="1" name="file" :action="uploadUrl" :show-file-list="false"
          :on-success="handleUploadSuccess">
          <img v-if="ruleForm.qr" width="80" height="80" :src="ruleForm.qr" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        <el-button type="primary" :loading="submitting" @click="submitForm('ruleForm')">立即创建</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
import { hostURL } from '@/plugins/utils/config'
import userApi from '@/plugins/api/user'
import uploadApi from '@/plugins/api/upload' // 添加缺失的导入
import configApi from '@/plugins/api/config'
import { userCaozuo } from '@/plugins/utils/caozuojilu'
export default {
  name: 'UserCreate',
  data() {
    return {
      token: '',
      allUser: [],
      listLoading: false, // 添加缺失的变量
      submitting: false, // 提交状态
      uploadUrl: hostURL + '/upload',
      config: [],
      ruleForm: {
        nickName: '',
        gender: 0,
        phone: '',
        avr: '',
        password: '',
        balance: 0,
        role: 2,
        online: false,
        qr: '',
        parent: null
      },
      rules: {
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入用户手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
        ],
        parent: [
          { required: true, message: '请选择邀请人', trigger: 'change' }
        ],
        qr: [
          { required: false }
        ]
      }
    }
  },
  mounted() {
    this.getConfig()
    this.getAllUser()
  },
  methods: {
    async getConfig() {
      const res = await configApi.list()
      if (res.code === 200) {
        this.config = res.data
        this.ruleForm.yajin = this.getYajinConfig()
      } else {
        this.$message.error('获取系统配置出错')
      }
    },
    async getAllUser() {
      const res = await userApi.all()
      console.log('getAllUser -> ', res);
      if (res.code === 200) {
        this.allUser = res.data
      } else {
        this.$message.error('获取用户列表出错')
      }
    },
    getUser(role) {
      if (!role) {
        return this.allUser.filter(item => item.role === 2 || item.role === 3)
      }
      return this.allUser.filter(item => item.role === role)
    },
    getYajinConfig() {
      const yajin = this.config.find(item => item.name === 'yajin')
      return yajin.value
    },

    handleUploadSuccess(res) {
      console.log(res);

      if (res.code === 200) {
        this.ruleForm.qr = `${hostURL}/uploads/${res.data}` // 修正字段名
        console.log(this.ruleForm);
        
        this.$message.success('上传成功!')
      } else {
        this.$message.error(res.message || '上传失败')
      }
    },


    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.create()
        } else {
          this.$message.warning('请填写完整表单信息')
          return false
        }
      })
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 创建用户
    async create() {
      console.log(this.ruleForm);

      this.submitting = true
      try {
        const res = await userApi.add(this.ruleForm)
        if (res.code === 200) {
          await userCaozuo.add(this.ruleForm)
          await this.$confirm('创建成功，是否退出创建用户页面', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
          })
          this.$router.push('/player/index')
        } else {
          this.$message.error(res.message || '创建失败')
        }
      } catch (err) {
        console.error('创建用户失败:', err)
        this.$message.error(err.message || '创建用户失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  box-sizing: border-box;
  margin: 24px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>